package com.nstc.sftpExchange.config.sftp;

import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Component;
import java.util.List;

@Getter
@Setter
@Component
public class FtpTemplateRegistrarProcessor {

    private SftpConfigProperties sftpConfigProperties;
    private SftpRoutingPool sftpRoutingPool;
    private ConfigurableListableBeanFactory beanFactory;


    public FtpTemplateRegistrarProcessor(SftpConfigProperties sftpConfigProperties,
                                         SftpRoutingPool sftpRoutingPool,
                                         ConfigurableListableBeanFactory beanFactory){
        this.sftpConfigProperties = sftpConfigProperties;
        this.sftpRoutingPool = sftpRoutingPool;
        this.beanFactory = beanFactory;
    }

    public void registerFtpTemplates() {
        if (sftpConfigProperties == null || sftpConfigProperties.getSftp() == null) {
            return;
        }

        List<SftpConfigProperties.SftpConfig> sftpConfigs = sftpConfigProperties.getSftp();

        for (SftpConfigProperties.SftpConfig config : sftpConfigs) {
            // 构建 FtpConnectionKey
            FtpConnectionKey connectionKey = new FtpConnectionKey();
            connectionKey.setHost(config.getHost());
            connectionKey.setPort(config.getPort());
            connectionKey.setUsername(config.getUsername());
            connectionKey.setPassword(config.getPassword());
            connectionKey.setName(config.getName());

            // 创建 FtpTemplate Bean 定义
            registerFtpTemplateBean(config.getName(), connectionKey);
        }
    }

    private void registerFtpTemplateBean(String beanName, FtpConnectionKey connectionKey) {
        if (beanFactory instanceof DefaultListableBeanFactory) {
            DefaultListableBeanFactory defaultBeanFactory = (DefaultListableBeanFactory) beanFactory;

            // 检查 Bean 是否已存在
            if (!defaultBeanFactory.containsBeanDefinition(beanName)) {
                // 创建 BeanDefinition
                BeanDefinitionBuilder builder = BeanDefinitionBuilder
                        .genericBeanDefinition(SftpTemplate.class);

                // 设置构造函数参数
                builder.addConstructorArgValue(beanName);
                builder.addConstructorArgValue(connectionKey);
                builder.addConstructorArgReference("sftpRoutingPool");

                // 注册 Bean
                defaultBeanFactory.registerBeanDefinition(beanName, builder.getBeanDefinition());
            }
        }
    }
}
